using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Bullet : MonoBehaviour
{
    // Start is called before the first frame update
    Vector3 movement;
    public float speed;
    public List<GameObject> smallBullet = new List<GameObject>();
    public float range;
    private float changeTime = 0;
    public float maxChangeTime;
    private float intervalTtime = 0;
    public float maxIntervalTtime;
    public float onceShootNumber;
    public float scatteringNumber;
    public float smallBulletSpeed;

    void Awake()
    {
        intervalTtime = 0;
    }
    void Start()
    {

        movement.x = speed;
        movement.y = range;
    }

    void Update()
    {

        MoveBullet();
        Launcher();
        if (transform.position.x < -11.2f)
        {
            Destroy(gameObject);
        }
        if (!Global.instance.StartFlag)
        {
            Destroy(gameObject);
        }


    }

    void Launcher()
    {
        intervalTtime += Time.deltaTime;
        if (intervalTtime >= maxIntervalTtime)
        {
            for (int i = 1; i <= onceShootNumber; i++)
            {
                Invoke("LaunchSmallBullet", .2f * i);
            }
            intervalTtime = 0f;
        }
    }

    void LaunchSmallBullet()
    {

        GetComponent<AudioSource>().Play();
        for (int i = 1; i <= scatteringNumber; i++)
        {
            //float y =  (2f * i / scatteringNumber -1f);
            float y = ((2f * i) / (scatteringNumber + 1)) - 1f;
            float x = (float)System.Math.Sqrt((float)(1 - System.Math.Pow(y, 2)));
            Vector2 Direction1 = new Vector2(-x, y);
            Launch(Direction1);
            Vector2 Direction2 = new Vector2(x, y);
            Launch(Direction2);
        }




    }



    void Launch(Vector2 Direction)
    {
        // Vector2 Direction = new Vector2(Random.Range(-1f,0f), Random.Range(-0.5f, 0.5f));
        GameObject bulletObject = Instantiate(smallBullet[Random.Range(0, smallBullet.Count)],
           transform.position,
           Quaternion.identity);
        Rigidbody2D bulletRigi = bulletObject.GetComponent<Rigidbody2D>();
        bulletRigi.AddForce(Direction * smallBulletSpeed);
    }

    void MoveBullet()
    {
        changeTime += Time.deltaTime;
        if (changeTime >= maxChangeTime || transform.position.y <= -4f || transform.position.y >= 4.3f)
        {

            movement.y *= -1f;
            changeTime = 0f;
        }
        transform.position -= movement * Time.deltaTime;
        
    }
}
